#include <stdio.h>
#include <stdlib.h>
#define length 4

int grayCode(char **space, char len, bool reverse);

int main()
{
    char **space = (char **)malloc(sizeof(char *) * (1 << length));
    if (space == NULL)
    {
        printf("Memory allocation failed\n");
        return 1;
    }
    register int i;
    for (i = 0; i < 1 << length; i++)
    {
        space[i] = (char *)malloc(sizeof(char) * (length + 1));
        if (space[i] == NULL)
        {
            printf("Memory allocation failed\n");
            return 1;
        }
        space[i][length] = '\0';
    }
    grayCode((char **)space, length, true);
    for (i = 0; i < 1 << length; i++)
    {
        printf("%s\n", space[i]);
    }
    return 0;
}

int grayCode(char **space, char len, bool reverse)
{
    char **newSpace = NULL;
    int iterator = 0;
    const int lim = 1 << (len - 1);
    if (len == 1)
    {
        space[0][0] = reverse ? '0' : '1';
        space[0][1] = '\0';
        space[1][0] = reverse ? '1' : '0';
        space[1][1] = '\0';
        return 0;
    }
    newSpace = (char **)malloc(sizeof(char *) * (1 << len));
    for (; iterator < lim; iterator++)
    {
        newSpace[iterator] = space[iterator] + 1;
        space[iterator][0] = reverse ? '0' : '1';
    }
    grayCode(newSpace, len - 1, reverse);
    for (iterator = 0; iterator < lim; iterator++)
    {
        newSpace[iterator] = space[iterator + lim] + 1;
        space[iterator + lim][0] = reverse ? '1' : '0';
    }
    grayCode(newSpace, len - 1, !reverse);
    free(newSpace);
    return 0;
}